package DBUtil

import (
	"database/sql"
	"demo_test/modifycollector/config"
	"errors"
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"strings"
)

func BuildConnection(cnf config.Config) string {
	var build strings.Builder
	build.WriteString(cnf.User)
	build.WriteString(":")
	build.WriteString(cnf.UserPwd)
	build.WriteString("@tcp(")
	build.WriteString(cnf.MysqlUrl)
	build.WriteString(`)/`)
	build.WriteString(cnf.Database)
	build.WriteString("?charset=utf8")
	dataSourceName := build.String()
	return dataSourceName
}

func ConnectMysql(dataSourceName string) (*sql.DB, error) {
	db, err := sql.Open("mysql", dataSourceName)
	if err != nil {
		fmt.Println(err)
		return nil, errors.New("连接数据库失败")
	}
	return db, nil
}

func GetRows(sqlstr string, db *sql.DB) (*sql.Rows, error) {
	rows, err := db.Query(sqlstr)
	if err != nil {
		fmt.Println(err.Error())
		return nil, errors.New("获取一行数据")
	}
	return rows, nil
}

func LoadAllData(rows *sql.Rows, res chan<- map[string]string) error {
	//读出查询出的列字段名
	cols, _ := rows.Columns()
	//values是每个列的值，这里获取到byte里
	values := make([][]byte, len(cols))
	//query.Scan的参数，因为每次查询出来的列是不定长的，用len(cols)定住单次查询的长度
	scans := make([]interface{}, len(cols))
	//让每一行数据都填充到[][]byte里面
	for i := range values {
		scans[i] = &values[i]
	}

	for rows.Next() {
		if err := rows.Scan(scans...); err != nil {
			fmt.Println(err.Error())
			return errors.New("数据采集失败")
		}
		mockdata := make(map[string]string, 10)
		for k, v := range values {
			key := cols[k]
			mockdata[key] = string(v)
		}
		res <- mockdata
	}
	rows.Close()
	return nil
}

func InsertDB(db *sql.DB, insertdata map[string]string) {
	stmt, _ := db.Prepare("INSERT INTO testbeat(username,pwd) VALUES (?,?)")
	stmt.Exec(insertdata["username"], insertdata["pwd"])
	stmt.Close()
}
